package com.hyl.message.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyl.message.constants.MQConstant;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

/**
 * @author leaf
 * @description TODO
 * @created 2023/7/20
 */
@Service
public class ProducerService {
    @Resource
    private RabbitTemplate rabbitTemplate;



    /**
     * 消息发送
     * @return
     */
    public boolean messageSend(Object param){
        //配置参数:参数格式以及编码格式
        MessageProperties mp = new MessageProperties();
        mp.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        mp.setContentEncoding("UTF-8");
        //以JSON的格式传输内容
        Message message = new Message(JSON.toJSONBytes(param), mp);
        //发送消息到队列中去，参数顺序： 交换机名称 ， routing key ， 消息对象
        rabbitTemplate.send(MQConstant.EXCHANGE_DIRECT_NAME,MQConstant.ROUTING_DIRECT,message);
        return true;
    }

    @Resource
    private ConnectionFactory connectionFactory;
    /**
     * 简单模式：消息发送
     * @param param
     * @return
     */
    public boolean messageSendSimple(Object param){
        Connection connection = null;
        Channel channel = null;
        try {
            //建立TCP长连接对象
            connection = connectionFactory.createConnection();
            //生成新的通道 参数为是否持久化，按需配置
            channel = connection.createChannel(false);

            //发送消息
            //消息参数配置
            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties(
                    MessageProperties.CONTENT_TYPE_JSON,    //contentType：内容类型
                    "UTF-8",    //contentEncoding：编码格式
                    null,       //headers：消息的header
                    1,          //deliveryMode：是否持久化 1非持久化 2持久化
                    1,          //priority：优先级
                    null,       //correlationId:关联ID
                    null,       //replyTo:用于指定回复的队列的名称
                    null,       //expiration:消息的失效时间
                    null,       //messageId:消息ID
                    new Date(), //timestamp:消息的时间戳
                    null,       //type:类型
                    "admin",    //userId:用户ID
                    null,       //appId：应用程序ID
                    null        //custerId:集群ID
            );
            //发送消息
            channel.basicPublish("",MQConstant.QUEUE_SIMPLE_NAME,basicProperties, JSONObject.toJSONBytes(param));
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            if (channel!=null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TimeoutException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                connection.close();
            }
        }
        return true;
    }

    /**
     * 工作模式：消息发送
     * @param param
     * @return
     */
    public boolean messageSendWork(Object param){
        Connection connection = null;
        Channel channel = null;
        try {
            //建立TCP长连接对象
            connection = connectionFactory.createConnection();
            //生成新的通道 参数为是否持久化，按需配置
            channel = connection.createChannel(false);

            //发送消息
            //消息参数配置
            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties(
                    MessageProperties.CONTENT_TYPE_JSON,    //contentType：内容类型
                    "UTF-8",    //contentEncoding：编码格式
                    null,       //headers：消息的header
                    1,          //deliveryMode：是否持久化 1非持久化 2持久化
                    1,          //priority：优先级
                    null,       //correlationId:关联ID
                    null,       //replyTo:用于指定回复的队列的名称
                    null,       //expiration:消息的失效时间
                    null,       //messageId:消息ID
                    new Date(), //timestamp:消息的时间戳
                    null,       //type:类型
                    "admin",    //userId:用户ID
                    null,       //appId：应用程序ID
                    null        //custerId:集群ID
            );
            //发送消息
            channel.basicPublish("",MQConstant.QUEUE_WORK_NAME,basicProperties, JSONObject.toJSONBytes(param));
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            if (channel!=null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TimeoutException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                connection.close();
            }
        }
        return true;
    }

    /**
     * 订阅分发模式：消息发送
     * @param param
     * @return
     */
    public boolean messageSendSub(Object param) {
        //配置参数:参数格式以及编码格式
        MessageProperties mp = new MessageProperties();
        mp.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        mp.setContentEncoding("UTF-8");
        //以JSON的格式传输内容
        Message message = new Message(JSON.toJSONBytes(param), mp);
        //只需要加入交换机名称
        rabbitTemplate.send(MQConstant.EXCHANGE_FANOUT_NAME , "", message);
        return true;
    }
}
